import React, { FC, useEffect } from 'react';
import { Routes, Route, useNavigate, Navigate, useLocation } from 'react-router-dom';
import { getCookie } from '@/config/globalConfig';
import App from './App';
import Sign_In from '@/pages/Sign_In/index';
import { menuConfig } from '@/config/menuConfig';

const Router: FC = () => {
  const userKey = getCookie().userKey;
  const navigate = useNavigate();
  const { pathname } = useLocation();

  useEffect(() => {
    if (!userKey) {
      navigate('/Sign_In');
    } else if (pathname === '/Sign_In') {
      navigate('/');
    }
  }, [pathname]);

  return (
    <Routes>
      {userKey ? (
        <>
          <Route path="/" element={<Navigate to="/app/al" />}></Route>
          <Route path="/app" element={<App />}>
            {menuConfig.map((item) => {
              return <Route path={item.path} key={item.id} element={<item.component />}></Route>;
            })}
          </Route>
        </>
      ) : (
        <Route path="/Sign_In" element={<Sign_In />}></Route>
      )}
    </Routes>
  );
};

export default Router;
